package com.domi.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.factory.rewrite.RewriteFunction;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

@Configuration
public class GatewayRouterConfig {

    @Bean
    public RouteLocator routeLocator(RouteLocatorBuilder builder, ObjectMapper mapper) {
        return builder.routes()
                .route("Route_ModifyRequestBody", predicate -> predicate.path("/book/**").and()
                        .method(HttpMethod.GET, HttpMethod.POST)
                        .filters(filter -> filter.modifyRequestBody(String.class, String.class, new RequestBodyRewriteFunction(mapper)))
                        .uri("lb://book-center")).build()
                ;
    }

    static class RequestBodyRewriteFunction implements RewriteFunction<String, String> {

        private ObjectMapper mapper;

        public RequestBodyRewriteFunction(ObjectMapper mapper) {
            this.mapper = mapper;
        }

        @Override
        public Publisher<String> apply(ServerWebExchange serverWebExchange, String s) {
            try {
                Map<String, Object> map = Objects.isNull(s) ? new HashMap<>() : mapper.readValue(s, Map.class);
                map.put("traceId", UUID.randomUUID().toString());
                return Mono.just(mapper.writeValueAsString(map));
            } catch (Throwable e) {
                e.printStackTrace();
                return Mono.just(s);
            }
        }

    }

}